import random
from captcha.image import ImageCaptcha
import io
import base64
#char_list是一个字符类型的列表，len:指定的长度
def getByLengthRomdom(char_list,len):
    char_list1 = random.sample(char_list, len)
    str = "".join(char_list1)
    return str

def getCaptchaImageBase64ByList(char_list,len):
    str = getByLengthRomdom(char_list,len)
    image = ImageCaptcha().generate_image(str)
    byteIo = io.BytesIO()
    image.save(byteIo,format='jpeg')
    byteIoValue = byteIo.getvalue()
    base64_str = base64.b64encode(byteIoValue).decode('utf-8')
    return 'data:image/jpeg;base64,'+ base64_str

def getCaptchaImageBase64ByStr(text):
    image = ImageCaptcha().generate_image(text)
    byteIo = io.BytesIO()
    image.save(byteIo,format='jpeg')
    byteIoValue = byteIo.getvalue()
    base64_str = base64.b64encode(byteIoValue).decode('utf-8')
    return 'data:image/jpeg;base64,'+ base64_str
